//
//  PlayingViewController.m
//  storyTest
//
//  Created by 史沐卉 on 2018/12/4.
//  Copyright © 2018 Facebook. All rights reserved.
//

#import "PlayingViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <notify.h>
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
//#import "RCTBridge.h"
#import <React/RCTEventDispatcher.h>

@class RCTBridge;

#define SONGNAME @"多幸运"

@interface PlayingViewController ()
@property (nonatomic, strong) AVAudioPlayer * player;
@end
@implementation PlayingViewController
RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(viewDidLoad) {
  //  [super viewDidLoad];
  NSLog(@"开始");

  
  
//  [self.player play];
  
  [self playControl];
  
  //添加远程锁屏控制
  [self createRemoteCommandCenter];
  
//  [self calendarEventReminderReceived:@"开始监控"];
  
}

- (AVAudioPlayer *)player{
  NSLog(@"开始2");
  if (_player == nil) {
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"./多幸运.mp3" withExtension:nil];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  }
  return _player;
}

//播放控制和监测
- (void)playControl {
  NSLog(@"开始3");
  //后台播放音频设置,需要在Capabilities->Background Modes中勾选Audio,Airplay,and Picture in Picture
  AVAudioSession *session = [AVAudioSession sharedInstance];
  
  [session setCategory:AVAudioSessionCategoryPlayback error:nil];
  
  [session setActive:YES error:nil];
  
  //展示锁屏歌曲信息，上面监听屏幕锁屏和点亮状态的目的是为了提高效率
//  [self showLockScreenTotaltime: duration current: current];
  
}

//展示锁屏歌曲信息：图片、歌词、进度、演唱者 播放速率
RCT_EXPORT_METHOD(showLockScreenTotaltime:(NSString *)name author: (NSString *)author parentName: (NSString *)parentName duration: (float) duration current:(float)current rate:(int)rate) {
  NSLog(@"开始4");
  NSLog(@"duration = %0.7g", duration);
  NSLog(@"current = %0.7g", current);
  NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init];
  //设置歌曲题目
  [songDict setObject:name forKey:MPMediaItemPropertyTitle];
  //设置歌手名
  [songDict setObject:author forKey:MPMediaItemPropertyArtist];
  //设置专辑名
  [songDict setObject:parentName forKey:MPMediaItemPropertyAlbumTitle];
  //设置歌曲时长
  [songDict setObject:[NSNumber numberWithFloat: duration]  forKey:MPMediaItemPropertyPlaybackDuration];
  //设置已经播放时长
  [songDict setObject:[NSNumber numberWithFloat: current] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
  //设置播放速率
  //注意：MPNowPlayingInfoCenter的rate 与 self.player.rate 是不同步的，也就是说[self.player pause]暂停播放后的速率rate是0，但MPNowPlayingInfoCenter的rate还是1，就会造成 在锁屏界面点击了暂停按钮，这个时候进度条表面看起来停止了走动，但是其实还是在计时，所以再点击播放的时候，锁屏界面进度条的光标会发生位置闪动， 所以我们需要在暂停或播放时保持播放速率一致
  [songDict setObject:[NSNumber numberWithInteger:rate] forKey:MPNowPlayingInfoPropertyPlaybackRate];
  
  NSData *data = [NSData  dataWithContentsOfURL:[NSURL URLWithString:@"http://img.alicdn.com/imgextra/i4/2457021025/TB298CQssj_B1NjSZFHXXaDWpXa_!!2457021025.jpg_430x430q90.jpg"]];
  
  UIImage *lrcImage =  [UIImage imageWithData:data];
//  UIImage * lrcImage = [UIImage imageNamed:@"http://img.alicdn.com/imgextra/i4/2457021025/TB298CQssj_B1NjSZFHXXaDWpXa_!!2457021025.jpg_430x430q90.jpg"];
    //设置显示的海报图片
    [songDict setObject:[[MPMediaItemArtwork alloc] initWithImage:lrcImage]
                 forKey:MPMediaItemPropertyArtwork];
  
  
  [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];
  
}


//-(BOOL)canBecomeFirstResponder{
//  return YES;
//}
///** 监听远程事件 */
//-(void)remoteControlReceivedWithEvent:(UIEvent *)event
//{
//  NSLog(@"remoteControlReceivedWithEvent");
//  switch (event.subtype) {
//    case UIEventSubtypeRemoteControlPlay: // 播放
//    case UIEventSubtypeRemoteControlStop: // 暂停
//      //      [self playOrPause]; // 控制播放与暂停
//      break;
//    case UIEventSubtypeRemoteControlNextTrack: // 下一首
//      //      [self next]; // 控制播放下一首
//
//      break;
//    case UIEventSubtypeRemoteControlPreviousTrack: // 上一首
//      //      [self previous]; // 控制播放上一首
//      break;
//    default:
//      break;
//  }
//}

//锁屏界面开启和监控远程控制事件
- (void)createRemoteCommandCenter{
  //RCT_EXPORT_METHOD(createRemoteCommandCenter:(RCTResponseSenderBlock) callback){
  /**/
  //远程控制命令中心 iOS 7.1 之后
  
  MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  
  //   MPFeedbackCommand对象反映了当前App所播放的反馈状态. MPRemoteCommandCenter对象提供feedback对象用于对媒体文件进行喜欢, 不喜欢, 标记的操作. 效果类似于网易云音乐锁屏时的效果
  [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"暂停播放");
    [self calendarEventReminderReceived:@"暂停播放" time: [NSNumber numberWithFloat:0]];
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"继续播放");
    [self calendarEventReminderReceived:@"继续播放" time: [NSNumber numberWithFloat:0]];
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"耳机");
    [self calendarEventReminderReceived:@"耳机" time: [NSNumber numberWithFloat:0]];
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"下一首");
    [self calendarEventReminderReceived:@"下一首" time: [NSNumber numberWithFloat:0]];
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"上一首");
    [self calendarEventReminderReceived:@"上一首" time: [NSNumber numberWithFloat:0]];
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  //在控制台拖动进度条调节进度（仿QQ音乐的效果）
  [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
    NSLog(@"进度条");
    NSLog(@"当前时间为%f", playbackPositionEvent.positionTime);
    [self calendarEventReminderReceived:@"进度条" time: [NSNumber numberWithFloat: playbackPositionEvent.positionTime]];
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  
}

@synthesize bridge = _bridge;
//  进行设置发送事件通知给JavaScript端
- (void)calendarEventReminderReceived:(NSString *)name time:(NSNumber *)time
{
//  NSLog(@"发送事件通知");
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": name, @"time": time}];
}
@end
